package it.xiuxian.homepage.activity
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import it.xiuxian.homepage.R
import it.xiuxian.homepage.bean.DetailBean
import it.xiuxian.homepage.databinding.HomepageZixunDetailBinding
import it.xiuxian.homepage.presenter.ZiXunDetailActivityPresenter
import it.xiuxian.lib.base.App
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseActivity
import it.xiuxian.lib.http.HttpConfig
import it.xiuxian.lib.utils.DensityUtil
import it.xiuxian.lib.utils.SPUtil
import it.xiuxian.lib.utils.Util
import kotlinx.android.synthetic.main.homepage_head.view.*
import kotlinx.android.synthetic.main.homepage_zixun_detail.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer


@Route(path = ArouterAddress.ZIXUNDETAILACTIVITY)
class ZiXunDetailActivity:BaseActivity<ZiXunDetailActivityPresenter>() {
    var erweima:String?=null
@JvmField
@Autowired
var id:String?=null
    @JvmField
    @Autowired
    var biaoti:String?=null
    @JvmField
    @Autowired
    var imgurl:String?=null

    override val layoutId: Int
        get() = R.layout.homepage_zixun_detail
    override val presenter: ZiXunDetailActivityPresenter
        get() = ZiXunDetailActivityPresenter()
    @SuppressLint("UseCompatLoadingForDrawables")
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun geData(data: DetailBean){
        var binding = getViewDataBinding<HomepageZixunDetailBinding>()
        (binding.include.re.layoutParams as LinearLayout.LayoutParams).setMargins(0, DensityUtil.getStatusPix(
                App.INSTANCE.applicationContext) + 25, 0, 0)
        binding.include.ivRight.visibility = View.VISIBLE
        //binding.include.rightTv.text ="分享"
        binding.include.ivRight.setImageDrawable(getDrawable(R.mipmap.lib_fen))
        binding.include.ivRight.setOnClickListener {
            regToWx()
            sendWx()
            SPUtil.put("id", id!!)
        }
        binding.include.leftImg.imageTintList= ColorStateList.valueOf(getColor(R.color.libTextBlack))
        binding.include.tvTitle.setTextColor(getColor(R.color.libTextBlack))
        binding.web.loadDataWithBaseURL(null, data.message, "text/html", "utf-8", null)
       // RichText.from(data.message).into(binding.tv)
        erweima = SPUtil.get("erweima", "")
    }
    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private val APP_ID = "wxf58b045a6e5b7f2b"

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null
    private fun regToWx(){
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true)

        // 将应用的appId注册到微信
        api!!.registerApp(APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该app注册到微信
                api!!.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }
    private val mTargetScene = SendMessageToWX.Req.WXSceneSession
  lateinit var bitmap:Bitmap
    lateinit var buffer:ByteBuffer
    private fun sendWx(){
        //初始化一个 WXTextObject 对象，填写分享的文本内容
        //初始化一个 WXTextObject 对象，填写分享的文本内容
        Log.e("erweima", erweima!!)
        val webpage = WXWebpageObject()
        webpage.webpageUrl =HttpConfig.BASE_URL+"/zixun/index.html?id="+id+"&pic="+erweima
        val msg = WXMediaMessage(webpage)

//用 WXTextObject 对象初始化一个 WXMediaMessage 对象
//用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        //val msg = WXMediaMessage()
        msg.title =biaoti
        msg.description ="更多内容，点击进入打工宇宙app"
      /* // msg.mediaObject = textObj
        msg.description = HttpConfig.BASE_URL+"/zixun/index.html?id="+id+"&pic="+erweima*/
       // val thumbBmp: Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.anquanzhongxin)
       /* Thread(Runnable{
          var mybitmap =  Glide.with(this).asBitmap()
                    .load(imaurl).submit(100,100).get()
             bitmap= Bitmap.createBitmap(mybitmap,0,0,mybitmap.width,mybitmap.height)

           }).start()*/
      //  Log.e("bitmap",bitmap.toString())
      /*  buffer = ByteBuffer.allocate(bitmap.byteCount)
        bitmap.copyPixelsToBuffer(buffer)
       var d =  buffer.array().size
        Log.e("bitmap",d.toString())*/
        msg.thumbData= Util.bmpToByteArray(bitmap,false)
        // =Util.bmpToByteArray(thumbBmp, true);
        val req = SendMessageToWX.Req()
        req.transaction = System.currentTimeMillis().toString() //transaction字段用与唯一标示一个请求
        req.message = msg
        req.scene = mTargetScene
        //调用api接口，发送数据到微信
        api!!.sendReq(req)
     /* var buffer = ByteBuffer.allocate(thumbBmp.byteCount)
        thumbBmp.copyPixelsToBuffer(buffer)
        msg.thumbData= buffer.array()
       // =Util.bmpToByteArray(thumbBmp, true);
        val req = SendMessageToWX.Req()
        req.transaction = System.currentTimeMillis().toString() //transaction字段用与唯一标示一个请求

        req.message = msg
        req.scene = mTargetScene
//调用api接口，发送数据到微信
        api!!.sendReq(req)*/
    }
    override fun initView(){
        ARouter.getInstance().inject(this)
        setTitle("资讯详情")

        lifecycleScope.launchWhenCreated {

            withContext(Dispatchers.IO){
                var mybitmap =  Glide.with(App.INSTANCE).asBitmap()
                    .load(imgurl).submit(100,100).get()
                bitmap= Bitmap.createBitmap(mybitmap,0,0,mybitmap.width,mybitmap.height)
                Log.e("bitmap",bitmap.byteCount.toString())
               // Log.e("bitmap",bitmap.byteCount.toString())
            }
        }

    }
    override fun initData(){
        mPresenter!!.getDetail(id!!)
    }
}